package hyj.qx.kuaican.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 请求工具类，用于处理HTTP请求相关的操作
 */
public class RequestUtil {
    /**
     * 从请求中获取参数，并将其解析为JSONObject对象
     *
     * @param request HTTP请求对象
     * @return 解析后的JSON对象
     * @throws IOException 如果读取或解析过程中发生I/O错误
     */
    public static JSONObject getParam(HttpServletRequest request) throws IOException {
        // 使用BufferedReader读取请求的输入流，并指定UTF-8字符集
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        // 构建字符串，用于存储读取到的请求体
        StringBuilder responsestrBuilder = new StringBuilder();
        String inputstr;
        // 循环读取请求体中的每一行，直到读取完毕
        while ((inputstr = streamReader.readLine()) != null) {
            responsestrBuilder.append(inputstr);
        }
        // 将读取到的请求体字符串解析为JSONObject对象
        return JSONObject.parseObject(responsestrBuilder.toString(), JSONObject.class);
    }

    /**
     * 从请求中获取表单数据，并将其解析为JSONObject对象
     *
     * @param request HTTP请求对象
     * @return 包含表单数据的JSON对象
     */
    public static JSONObject getFormData(HttpServletRequest request) throws IOException {
        JSONObject formData = new JSONObject();
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items1 = upload.parseRequest(request);
            for (FileItem item : items1) {
                if (item.isFormField()) {
                    // 处理普通表单字段
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString(StandardCharsets.UTF_8.name());
                    formData.put(fieldName, fieldValue);
                }
            }
        } catch (FileUploadException e) {
            throw new IOException("Error parsing multipart/form-data", e);
        }
        return formData;
    }

}